package com.yanfan.energybilling.controller;

import com.yanfan.common.core.controller.BaseController;
import com.yanfan.common.core.domain.AjaxResult;
import com.yanfan.common.utils.poi.ExcelUtil;
import com.yanfan.energybilling.domain.TDEnergyDeductionRecord;
import com.yanfan.energybilling.service.IRecordImportService;
import com.yanfan.framework.manager.AsyncManager;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.TimerTask;

@Slf4j
@RestController
@RequestMapping("/recordImport")
public class RecordImportController extends BaseController {
    @Autowired
    private IRecordImportService recordImportService;

    /**
     * 导入数据
     */
    @ApiOperation("导入列表")
    @PostMapping("/import")
    public AjaxResult recordImport(MultipartFile file) throws Exception {
        ExcelUtil<TDEnergyDeductionRecord> util = new ExcelUtil<>(TDEnergyDeductionRecord.class);
        List<TDEnergyDeductionRecord> recordList = util.importExcel(file.getInputStream());
        AsyncManager.me().execute(new TimerTask() {
            @Override
            public void run() {
                String message = recordImportService.recordImport(recordList);
                log.info("数据导入：{}", message);
            }
        });

        return success("数据正在后台执行，请勿重复导入！");
    }

    /**
     * 下载导入模板
     */
    @ApiOperation("下载导入模板")
    @PostMapping("/importTemplate")
    public void importTemplate(HttpServletResponse response) {
        ExcelUtil<TDEnergyDeductionRecord> util = new ExcelUtil<>(TDEnergyDeductionRecord.class);
        util.importTemplateExcel(response, "数据");
    }
}
